﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Obligatorio2013.Clases;
using System.Xml;
using Obligatorio2013.Logging;
using System.Xml.Linq;

namespace Obligatorio2013.Persistencia.Daos
{
    public class PricesDAO : PersistentDAO
    {

        private string pricesFileName = "prices.xml";

        public override bool Save(object obj)
        {
            try
            {
                if (!FileExist(pricesFileName))
                {
                    createFileXml(path, pricesFileName, "Prices");
                }

                if (obj != null)
                {
                    // Crear un nuevo elemento 
                    Price p = obj as Price;

                    XmlDocument doc = LoadXmlFile(path, pricesFileName);
                    XmlElement newElement = doc.CreateElement("Price");

                    addAttribute(doc, newElement, "date", p.changeDate.ToString());
                    // Crear los nodos hijos.
                    addElement(doc, newElement, "basic", p.basicCost.ToString());
                    addElement(doc, newElement, "premium", p.premiumCost.ToString());
                    addElement(doc, newElement, "percent", p.percent.ToString());
                    // agregar el elemento al final de la lista de elementos.
                    doc.DocumentElement.AppendChild(newElement);
                    doc.Save(path + this.pricesFileName);
                    return true;
                }

            }
            catch (Exception ex)
            {
                Log.Instance.Error("Error salvando Precio." +ex.Message, ex.StackTrace);
                //throw ex;
            }
            return false;
        }


        public override List<object> getAll()
        {
            try
            {
                XmlReader reader = XmlReader.Create(path + "\\" + pricesFileName);
                List<Object> prices = null;
                XElement element = XElement.Load(reader, LoadOptions.SetBaseUri);
                IEnumerable<XElement> items = element.DescendantsAndSelf("Price");

                if (reader != null)
                {
                    prices = new List<Object>();
                    foreach (var xElement in items)
                    {                        
                        Price p = new Price();

                        String dateAux = GetAttributeValue("date", xElement); ;
                        p.changeDate = DateTime.Parse(dateAux);

                        string basic = GetElementValue("basic", "string", xElement);
                        string premium = GetElementValue("premium", "string", xElement);
                        string percent = GetElementValue("percent", "string", xElement);
                        p.basicCost = Double.Parse(basic);
                        p.premiumCost = Double.Parse(premium);
                        p.percent = Double.Parse(percent);
                        prices.Add(p);
                    }
                }
                return prices;
            }
            catch (Exception ex)
            {
                Log.Instance.Error("Error obteniendo precios. " + ex.Message, ex);
                throw ex;
            }
        }

        public override bool Update(object objId)
        {
            if (FileExist(pricesFileName))
            {
                Price p = objId as Price;
                XmlDocument doc = LoadXmlFile(path, pricesFileName);
                XmlNode priceNode = getElementByID(doc, "Price", "date", p.changeDate.ToString());


                doc.RemoveChild(priceNode);
                if (priceNode != null)
                {
                    try
                    {
                        //priceNode.Attributes["date"].Value = p.changeDate.ToLongDateString();
                        priceNode["basic"].InnerText = p.basicCost.ToString();
                        priceNode["premium"].InnerText = p.premiumCost.ToString();
                        priceNode["percent"].InnerText = p.percent.ToString();
                      
                        doc.Save(path + pricesFileName);
                        return true;
                    }
                    catch (Exception ex)
                    {
                        Logging.Log.Instance.Error("Error modificando precio." + ex.Message, ex);
                        throw new Exception();
                    }
                }
            }
            return false;
        }

        public override bool Delete(object objId)
        {


            try
            {
                if (FileExist(pricesFileName))
                {
                    Price p = objId as Price;
                    XmlDocument doc = LoadXmlFile(path, pricesFileName);
                    XmlNode priceNode = getElementByID(doc, "Price", "date", p.changeDate.ToLongDateString());
                    doc.RemoveChild(priceNode);
                    return true;
                }
            }
            catch (Exception ex)
            {
                Log.Instance.Error("No fue posible eliminar el nodo. "+ex.Message,ex);
                throw ex;
            }
            return false;
        }
    }
}